﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.Net.InformationPlatform.Entity;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.Net.InformationPlatform.Service.Equipment.Dto;
using Admin.Net.InformationPlatform.Entity.Equipment;
using Furion.FriendlyException;
using Admin.NET.Core;

namespace Admin.Net.InformationPlatform.Service.Equipment;

/// <summary>
/// 设备管理系统 设备保养
/// </summary>
[ApiDescriptionSettings(groups: "HWYC", Name = "保研信息管理", Tag = "设备保养", Order = 200)]
[Route("HWYC/")]
public class MaintenanceMessageService : IDynamicApiController, ITransient
{
    /// <summary>
    /// 单例数据链接
    /// </summary>
    ISqlSugarClient db;
    /// <summary>
    /// T100数据库
    /// </summary>
    private SqlSugarProvider _T100Db;
    private SqlSugarProvider _SjDb;
    private SqlSugarProvider _plm;
    private SqlSugarProvider _Dilon;


    /// <summary>
    /// 用户信息
    /// </summary>
    TokenUser _User;
    /// <summary>
    /// SOP工程文件管理
    /// </summary>
    /// <param name="db"></param>
    public MaintenanceMessageService(ISqlSugarClient db)
    {
        this.db = db;
        this._T100Db = this.db.AsTenant().GetConnection(T100TestArea.ConfigId);
        this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
        this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
        this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
        // 获取 `Jwt` 存储的信息 企业编号与据点信息
        _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

    }

    /// <summary>
    /// 添加 保养记录信息
    /// </summary>
    /// <returns></returns>
    [HttpPost("/SaveEqipmentMaintenanceMessage")]
    public async Task<string> SaveEqipmentMaintenanceMessage(MaintenanceMessageInput input) {

        //判断单据存在
        int cnt =  _SjDb.Queryable<HWEquipmentBasicInformation>()
            .Where(a => a.DEVICENUMBER == input.DEVICENUMBER)
            .Where(a => a.LIFECYCLE ==0)
           .Count();

        if (cnt == 0)
        {

            throw Oops.Oh("任务不存在，驳回！");
        }
        else {

            HWMaintenanceMessage maintenanceMessage = new HWMaintenanceMessage() { 
            DEVICENUMBER = input.DEVICENUMBER,
            MAINTENANCETIME = DateTime.Now,
            MAINTENANCEPERSON = input.MAINTENANCEPERSON,
            MAINTENANCEEXPENSES = input.MAINTENANCEEXPENSES,
            MAINTENANCECAUSE = input.MAINTENANCECAUSE,
            MAINTENANCEREMARK = input.MAINTENANCEREMARK

            };



            #region 插入事务
            try
            {
                //开启事务
                _SjDb.Ado.BeginTran();
                int count = await _SjDb.Insertable<HWMaintenanceMessage>(maintenanceMessage).ExecuteCommandAsync();

                if (count == 0)
                {
                    throw Oops.Oh($"新建任务失败！");
                }
                //提交事务
                _SjDb.Ado.CommitTran();
                return "插入成功";
            }
            catch (Exception e)
            {
                //回滚事务
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }
            #endregion

        }


    }

    /// <summary>
    /// 查询 保养记录信息
    /// </summary>
    [HttpPost("/SeleteEqipmentMaintenanceMessage")]
    public async Task<SqlSugarPagedList<HWMaintenanceMessage>> SeleteEqipmentMaintenanceMessage(SeleteMaintenanceMessageInput input) {

        var output = await _SjDb.Queryable<HWMaintenanceMessage>()
               .WhereIF(!string.IsNullOrEmpty(input.DEVICENUMBER), (l) => (l.DEVICENUMBER.Contains(input.DEVICENUMBER)))//设备编号
               .WhereIF(!string.IsNullOrEmpty(input.MAINTENANCEPERSON), (l) => (l.MAINTENANCEPERSON.Contains(input.MAINTENANCEPERSON)))//保养人
               .WhereIF(!string.IsNullOrEmpty(input.MAINTENANCECAUSE), (l) => (l.MAINTENANCECAUSE.Contains(input.MAINTENANCECAUSE)))//保养原因
               .WhereIF(input.StateMaintenanceTime != null, b => (SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(b.MAINTENANCETIME), "yyyy-mm-dd"), "yyyy-mm-dd") >= input.StateMaintenanceTime))//保养日期 开始时间
               .WhereIF(input.EndMaintenanceTime != null, b => (SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(b.MAINTENANCETIME), "yyyy-mm-dd"), "yyyy-mm-dd") <= input.EndMaintenanceTime))//保养日期 结束时间

               .OrderBy(l => l.MAINTENANCETIME, OrderByType.Desc) //创建日期排序
               .Select(l => new HWMaintenanceMessage
               {
                   MID = l.MID,
                   DEVICENUMBER = l.DEVICENUMBER,
                   MAINTENANCETIME = l.MAINTENANCETIME,
                   MAINTENANCEPERSON = l.MAINTENANCEPERSON,
                   MAINTENANCEEXPENSES = l.MAINTENANCEEXPENSES,
                   MAINTENANCECAUSE = l.MAINTENANCECAUSE,
                   MAINTENANCEREMARK = l.MAINTENANCEREMARK,

               }).ToPagedListAsync(input.Page, input.PageSize);

        return output;
    }


    /// <summary>
    /// 查询 设备的保养状态
    /// </summary>
    [HttpPost("/SeleceEqipmentMaintenanceState")]
    public async void SeleceEqipmentMaintenanceState() { 
    
    
    
    }
}
